package com.affectu.search;

import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.ChineseAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;

import com.affectu.common.base.UtilBase;

/**
 * Oct 10, 2008
 * 
 * @author daniel nathan
 */
public class LuceneUtil extends UtilBase {

	private static LuceneUtil instance = new LuceneUtil();

	private Analyzer analyzer = new ChineseAnalyzer();

	private SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
			"<b><font color='red'>", "</font></b>");

	private LuceneUtil() {
	}

	public static LuceneUtil getInstance() {
		return instance;
	}

	public Query getLuceneQuery(String[] fields, String searchQuery) {
		Query luceneQuery = null;
		try {
			QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
			luceneQuery = parser.parse(searchQuery);
		} catch (ParseException pex) {
			this.logException(pex);
		} catch (Exception ex) {
			this.logException(ex);
		}
		return luceneQuery;
	}

	public String getHighlighterText(String field, String[] taskFields,
			String highlightedText, String searchQuery) {
		String outputText = highlightedText;
		try {
			Highlighter highlighter = new Highlighter(simpleHTMLFormatter,
					new QueryScorer(getLuceneQuery(taskFields, searchQuery)));
			highlighter.setTextFragmenter(new SimpleFragmenter(highlightedText
					.length() + 1));
			TokenStream tokenStream = analyzer.tokenStream(field,
					new StringReader(highlightedText));
			outputText = highlighter.getBestFragment(tokenStream,
					highlightedText);
			if (outputText == null || outputText.trim().equals("")) {
				outputText = highlightedText;
			}
		} catch (Exception ex) {
			this.logException(ex);
		}
		return outputText;
	}
}
